import util from '../libs/util';

export default {
  props: {
    exportParams: {
      type: Object
    }
  },
  data() {
    return {
      exportForm: {
        fileName: '',
        visible: false
      },
      view: {}
    };
  },
  computed: {
    exportFileName() {
      return (
        (this.exportParams && this.exportParams.fileName) ||
        (this.selectedView && this.selectedView.ViewName)
      );
    }
  },
  methods: {
    async exportViewData() {
      if (!rt.isNullOrWhiteSpace(this.exportParams.exportId)) {
        this.view = {
          Id: this.exportParams.exportId,
          ViewName: this.exportParams.fileName
        };
      } else {
        this.view = this.selectedView;
      }

      // if (rt.isNull(this.view) || rt.isNull(this.view.Id)) {
      //   return;
      // }

      if (this.preExport && typeof this.preExport === 'function') {
        if (!(await this.preExport())) {
          return;
        }
      }

      let headerMap = this.exportParams.headerMap;
      if (!headerMap) {
        headerMap = {};
        this.columns.forEach(col => {
          if (col.prop) {
            headerMap[col.prop] = col.label;
          }
        });
      }
      let param = {
        headerMap: headerMap,
        name: this.exportForm.fileName || this.exportFileName
      };

      let quickSearchList = [];
      if (this.inputSearchParam.length > 0) {
        this.inputSearchParam.forEach(key => {
          if (
            !rt.isNil(this.quickSearchValue) &&
            !rt.isNullOrWhiteSpace(this.quickSearchValue)
          ) {
            quickSearchList.push({ key: key, value: this.quickSearchValue });
          }
        });
      }
      if (!rt.isNilOrEmptyArray(quickSearchList)) {
        param.quickSearch = quickSearchList;
      }
      if (!rt.isNilOrEmptyArray(this.searchList)) {
        param.searchList = this.searchList;
      }
      if (!rt.isNilOrEmptyArray(this.orderByList)) {
        param.orderBy = this.orderByList;
      }

      const loading = this.$loading({
        lock: true,
        text: '正在导出成EXCEL文件，请稍等...',
        spinner: 'el-icon-loading'
      });

      try {
        const url = `api/${this.controllerName}/export`;
        // const res = await rt.post(url, reqData);
        let auth = this.$store.state.auth;
        util.commDownExcel(url, param, auth.accessToken);
        this.exportForm.visible = false;
        this.exportForm.fileName = '';
      } catch (error) {
        rt.showErrorToast(error.message);
      } finally {
        await this.$nextTick();
        loading.close();
      }
    }
  }
};
